<!-- 词汇分类分析 -->
<template>
  <div class="w-full statistical-center">
    <statisticalHeader />
    <div class="px-40px pb-60px m--9px flex flex-1 gap-10px flex-col">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-12px text-28px fw-700">
          <div class="flex items-center">
            <el-date-picker
              popper-class="popper-date-class"
              v-model="queryDate"
              type="daterange"
              placeholder="请选择日期"
              value-format="YYYYMMDD"
              :clearable="false"
            />
          </div>
          <ClassStudentCascader @change="cascaderChange" />
        </div>
        <div>
          <aiGenerateReport :sendContent="sendContent" :roleId="53" />
        </div>
      </div>
      <div class="flex gap-20px flex-1 flex-wrap" v-loading="loading">
        <div class="echart-card w-600px">
          <Echart
            :width="getViewportPx(600)"
            :height="getViewportPx(320)"
            :options="lengthStatOption"
          />
        </div>
        <div class="echart-card w-600px">
          <Echart
            :width="getViewportPx(600)"
            :height="getViewportPx(320)"
            :options="completeSentRatioOption"
          />
        </div>
        <div class="echart-card w-600px">
          <Echart
            :width="getViewportPx(600)"
            :height="getViewportPx(320)"
            :options="sentCountOption"
          />
        </div>
        <div class="echart-card w-909px">
          <Echart
            :width="getViewportPx(900)"
            :height="getViewportPx(320)"
            :options="logicConjunctionStatsOption"
          />
        </div>
        <div class="echart-card w-909px">
          <Echart
            :width="getViewportPx(900)"
            :height="getViewportPx(320)"
            :options="richnessOption"
          />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { getViewportPx } from '@/utils/formatter'
import { statisticalCenterApi } from '@/api/school/statisticalCenter/index'
import { useBarOptions } from '@/hooks/chart/useBarOptions'
import { useRadarOptions } from '@/hooks/chart/useRadarOptions'
import { useLiquidFillOptions } from '@/hooks/chart/useLiquidFillOptions'
import statisticalHeader from './components/statisticalHeader.vue'
import aiGenerateReport from './components/aiGenerateReport.vue'
import { getAxisNameConfig, getDataZoomConfig } from './utils'
import { formatDate } from '@/utils/formatTime'

const speechSentsData: any = ref({})
const logicalData: any = ref({})
const loading = ref(true)
const cascaderParams: any = ref({})
const pathLabels = ref([])
const nowDateStr = formatDate(new Date(), 'YYYYMMDD')
const queryDate = ref([nowDateStr, nowDateStr])
const queryParams = computed(() => {
  return {
    startTime: queryDate.value[0],
    endTime: queryDate.value[1],
    ...cascaderParams.value
  }
})

// 发送内容
const sendContent = computed(() => {
  const baseData = {
    startTime: queryParams.value.startTime,
    endTime: queryParams.value.endTime,
    type: pathLabels.value.length - 1,
    target: pathLabels.value.join('-'),
    data: `${JSON.stringify(speechSentsData.value)}${JSON.stringify(logicalData.value)}`
  }
  return baseData
})

// 请求接口
const requestApiMap = computed(() => {
  let sentsApi = statisticalCenterApi.getSchoolSentenceReport
  let logicalApi = statisticalCenterApi.getSchoolLogicalReport
  if (queryParams.value.studentId) {
    sentsApi = statisticalCenterApi.getSentsReport
    logicalApi = statisticalCenterApi.getLogicalReport
  } else if (queryParams.value.classId) {
    sentsApi = statisticalCenterApi.getClassSentenceReport
    logicalApi = statisticalCenterApi.getClassLogicalReport
  }

  return {
    sentsApi,
    logicalApi
  }
})

const init = async () => {
  if (!Object.keys(cascaderParams.value).length) {
    return
  }
  try {
    loading.value = true
    speechSentsData.value = await requestApiMap.value.sentsApi(queryParams.value)
    logicalData.value = await requestApiMap.value.logicalApi(queryParams.value)
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}
const cascaderChange = async (params, cascaderPathLabels) => {
  cascaderParams.value = params
  pathLabels.value = cascaderPathLabels
}
const lengthStatTypeMap = {
  simpleLengthStat: '单句',
  complexLengthStat: '复句'
}
const lengthStatOption = computed(() => {
  let nameMap = speechSentsData.value?.map?.((item) => item.className || item.studentName) || []
  let series: any = []
  if (!queryParams.value.studentId) {
    series = [
      {
        name: '单句',
        itemStyle: {
          color: '#8945FF'
        },
        data: speechSentsData.value?.map?.((item: any) => item.simpleLengthAvg || 0) || []
      },
      {
        name: '复句',
        itemStyle: {
          color: '#47D147'
        },
        data: speechSentsData.value?.map?.((item: any) => item.complexLengthAvg || 0) || []
      }
    ]
  } else {
    nameMap = Object.values(lengthStatTypeMap)
  }
  const dataMap = speechSentsData.value
    ? Object.keys(lengthStatTypeMap)
        ?.map?.((key) => speechSentsData.value[key])
        .filter(Boolean)
    : []
  return useBarOptions([], {
    title: {
      text: '单复句长度统计',
      left: 'center'
    },
    grid: {
      top: !cascaderParams.value?.studentId && nameMap.length > 6 ? getViewportPx(100, true) : '60',
      right: getViewportPx(15),
      left: getViewportPx(70)
    },
    dataZoom: !cascaderParams.value?.studentId && nameMap.length > 6 && [getDataZoomConfig()],
    legend: {
      right: getViewportPx(15)
    },
    yAxis: {
      ...getAxisNameConfig('单位：个')
    },
    xAxis: {
      data: nameMap
    },
    series: series.length
      ? series
      : [
          {
            name: '最长句子',
            itemStyle: {
              color: '#8945FF'
            },
            data: dataMap?.map?.((item: any) => item.max) || []
          },
          {
            name: '平均时长',
            itemStyle: {
              color: '#47D147'
            },
            data: dataMap?.map?.((item: any) => Math.floor(item.avg * 100) / 100) || []
          }
        ]
  }).baseOptions
})
const completeSentRatioOption = computed(() => {
  if (!queryParams.value.studentId) {
    return useBarOptions(
      speechSentsData.value?.map?.((item: any) => ({
        name: item.className || item.studentName,
        value: item.completeRatioAvg || item.completeRatio || 0,
        label: {
          formatter: function (params) {
            return `${Math.floor(params.value * 10000) / 100}%`
          }
        }
      })) || [],
      {
        title: {
          text: '完整句占比统计',
          left: 'center'
        },
        grid: {
          top:
            !cascaderParams.value?.studentId && speechSentsData.value.length > 6
              ? getViewportPx(100, true)
              : '60',
          right: getViewportPx(15),
          left: getViewportPx(70)
        },
        dataZoom: !cascaderParams.value?.studentId &&
          speechSentsData.value.length > 6 && [getDataZoomConfig()],
        tooltip: {
          formatter: function (params) {
            const paramsItem = params[0]
            return `${paramsItem.name}<br />${paramsItem.marker}比例: ${Math.floor(paramsItem.value * 10000) / 100}%`
          }
        },
        yAxis: {
          ...getAxisNameConfig('单位：比例'),
          axisLabel: {
            formatter(value) {
              return `${Math.floor(value * 10000) / 100}%`
            }
          }
        }
      }
    ).baseOptions
  }
  return useLiquidFillOptions([speechSentsData.value?.completeSentRatio || 0], {
    title: {
      text: '完整句占比统计',
      left: 'center'
    }
  }).baseOptions
})
const sentCountTypeMap = {
  单句: ['simpleSentCount', 'simpleSentRatio'],
  复句: ['complexSentCount', 'complexSentRatio']
}
const sentCountOption = computed(() => {
  let nameMap = speechSentsData.value?.map?.((item) => item.className || item.studentName) || []
  let series: any = []
  if (!queryParams.value.studentId) {
    series = [
      {
        name: '单句',
        itemStyle: {
          color: '#8945FF'
        },
        data:
          speechSentsData.value?.map?.(
            (item: any) => item.simpleCountAvg || item.simpleCount || 0
          ) || []
      },
      {
        name: '复句',
        itemStyle: {
          color: '#47D147'
        },
        data:
          speechSentsData.value?.map?.(
            (item: any) => item.complexCountAvg || item.complexCount || 0
          ) || []
      }
    ]
  } else {
    nameMap = Object.keys(sentCountTypeMap)
  }
  const dataMap = speechSentsData.value
    ? Object.values(sentCountTypeMap)?.map?.((value) => ({
        count: speechSentsData.value[value[0]],
        ratio: speechSentsData.value[value[1]]
      }))
    : []
  return useBarOptions([], {
    title: {
      text: '单复句数量统计',
      left: 'center'
    },
    grid: {
      top: !cascaderParams.value?.studentId && nameMap.length > 6 ? getViewportPx(100, true) : '60',
      right: getViewportPx(15),
      left: getViewportPx(70)
    },
    dataZoom: !cascaderParams.value?.studentId && nameMap.length > 6 && [getDataZoomConfig()],
    legend: {
      right: getViewportPx(15)
    },
    yAxis: {
      ...getAxisNameConfig('单位：个')
    },
    xAxis: {
      data: nameMap
    },
    series: series.length
      ? series
      : [
          {
            name: '数量',
            itemStyle: {
              color: '#8945FF'
            },
            data: dataMap?.map?.((item: any) => item.count) || []
          },
          {
            name: '占比',
            itemStyle: {
              color: '#47D147'
            },
            data: dataMap?.map?.((item: any) => Math.floor(item.ratio * 100 * 100) / 100) || []
          }
        ]
  }).baseOptions
})
const logicConjunctionStatsOption = computed(() => {
  let dataMap: any = []
  let legendData: any = []
  let logicConjunctionStats =
    logicalData.value?.logicConjunctionStats || logicalData.value?.[0]?.logicConjunctionStats
  const indicator = logicConjunctionStats
    ? Object.entries(logicConjunctionStats)?.map(([key, value]: any) => ({
        name: key,
        max: value.usedCount > value.totalCount ? value.usedCount : value.totalCount,
        value: value.usedCount
      }))
    : []
  if (!queryParams.value.studentId) {
    dataMap =
      logicalData.value?.map?.((item: any) => {
        legendData.push(item.className || item.studentName)
        return {
          name: item.className || item.studentName,
          value:
            Object.values(item.logicConjunctionStats)?.map(
              (subItem: any) => subItem.usedCountAvg || subItem.usedCount || 0
            ) || []
        }
      }) || []
  } else {
    dataMap = [
      {
        name: '统计',
        value: indicator.map((item) => item.value)
      }
    ]
  }

  return useRadarOptions(dataMap.length ? dataMap : [], {
    title: {
      text: '逻辑性表达统计',
      left: 'center'
    },
    legend: {
      show: !queryParams.value.studentId,
      type: 'scroll',
      orient: 'vertical',
      textStyle: {
        width: 100,
        overflow: 'truncate'
      },
      right: getViewportPx(20),
      top: 'center',
      data: !queryParams.value.studentId && legendData
    },
    radar: {
      shape: 'circle',
      axisName: {
        color: '#2ba8ff'
      },
      indicator: indicator,
      splitArea: {
        areaStyle: {
          color: '#00BFFF19',
          shadowColor: 'rgba(0, 0, 0, 0.2)',
          shadowBlur: 10
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(211, 253, 250, 0.8)'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(0, 191, 255, 0.5)'
        }
      }
    },
    series: [
      {
        // itemStyle: {
        //   color: '#00BFFF'
        // },
        areaStyle: {
          color: '#00BFFF'
        }
      }
    ]
  }).baseOptions
})
const richnessTypeMap = {
  sentenceRichness: '句子',
  paragraphRichness: '段落'
}
const richnessNameMap = {
  avgPosCount: '平均',
  maxPosCount: '最大'
}
const richnessOption = computed(() => {
  if (!queryParams.value.studentId) {
    return useBarOptions([], {
      title: {
        text: '词性丰富度统计',
        left: 'center'
      },
      grid: {
        top:
          !cascaderParams.value?.studentId && logicalData.value.length > 6
            ? getViewportPx(100, true)
            : '60',
        right: getViewportPx(15),
        left: getViewportPx(70)
      },
      dataZoom: !cascaderParams.value?.studentId &&
        logicalData.value.length > 6 && [getDataZoomConfig()],
      legend: {
        right: getViewportPx(15)
      },
      xAxis: {
        data: logicalData.value?.map?.((item: any) => item.className || item.studentName) || []
      },
      yAxis: {
        ...getAxisNameConfig('单位：个')
      },
      series: [
        {
          name: '段落',
          itemStyle: {
            color: '#8945FF'
          },
          data: logicalData.value?.map?.((item: any) => item.paragraphPosAvg || 0) || []
        },
        {
          name: '句子',
          itemStyle: {
            color: '#47D147'
          },
          data: logicalData.value?.map?.((item: any) => item.sentencePosAvg || 0)
        }
      ]
    }).baseOptions
  }
  const dataMap = richnessTypeMap
    ? Object.entries(richnessTypeMap)
        ?.map(([key, value]) => {
          const item = logicalData.value[key]
          if (item) {
            return Object.entries(richnessNameMap).map(([subKey, subValue]) => ({
              name: `${value}${subValue}`,
              value: item[subKey]
            }))
          }
        })
        ?.filter(Boolean)
    : []
  return useBarOptions(dataMap.flat().filter(Boolean), {
    title: {
      text: '词性丰富度统计',
      left: 'center'
    },
    grid: {
      right: getViewportPx(45),
      left: getViewportPx(90)
    },
    legend: {
      right: getViewportPx(15)
    },
    xAxis: {
      type: 'value',
      ...getAxisNameConfig('单位：个', {
        nameLocation: 'center',
        nameTextStyle: {
          padding: [parseInt(getViewportPx(10, true)), 0, 0, parseInt(getViewportPx(760, true))]
        }
      })
    }
  }).baseOptions
})

watch(
  () => queryParams.value,
  () => {
    init()
  },
  {
    immediate: true
  }
)
</script>
<style lang="scss" scoped>
@import url('./index.scss');

.echart-card {
  padding: 15px 0;
}
</style>
